﻿#region

using System;
using System.Web.Mvc;
using Tateeda.ClinicalStudy.Base.Modules.Infrastructure.Interfaces.Services;
using Tateeda.ClinicalStudy.Base.Modules.Models.StudyForm;
using Tateeda.ClinicalStudy.Base.Web.Common;

#endregion

#region - Legal -

///<legal>
/// Copyright © 2011, Tateeda Media Network
/// All rights reserved. http://tateeda.com
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions
/// are met:
///
/// - Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
///
/// - Neither the name of the Tateeda Media Network, nor the names of its
/// contributors may be used to endorse or promote products
/// derived from this software without specific prior written
/// permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
/// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
/// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
/// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
/// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
/// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
/// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
/// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
/// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
/// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///</legal>

#endregion - Legal -

namespace Tateeda.ClinicalStudy.Base.Web.Controllers {

    public class FormBuilderController : Controller {
        private readonly IFormBuilder _service;

        public FormBuilderController(IFormBuilder service) {
            _service = service;
        }

        [Authorize(Roles = Constants.RoleAdminAppuser)]
        [ValidateAntiForgeryToken]
        public ActionResult AnswerDelete(int id, int qid) {
            try {
                _service.DeleteAnswer(id);
                return RedirectToAction("Answers", new { questionId = qid });
            } catch (Exception ex) {
                ViewBag.Error = ex.Message;
                return View();
            }
        }

        [HttpPost]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        [ValidateAntiForgeryToken]
        public ActionResult AnswerEdit(AnswerModel answer) {
            try {
                answer.CreatedBy = HttpContext.User.Identity.Name;
                answer.UpdatedBy = HttpContext.User.Identity.Name;
                answer.CreatedOn = DateTime.UtcNow;
                answer.UpdatedOn = DateTime.UtcNow;
                if (answer.AnswerId > 0)
                    _service.EditAnswer(answer);
                else
                    _service.AddAnswer(answer);
                return RedirectToAction("Answers", new { questionId = answer.QuestionId });
            } catch (Exception) {
                return View();
            }
        }

        [Authorize(Roles = Constants.RoleAdminAppuser)]
        [ValidateAntiForgeryToken]
        public ActionResult AnswerEdit(int answerId, int questionId) {
            ViewBag.Question = _service.GetQuestion(questionId).QuestionText;
            ViewBag.QuestionId = questionId;

            var answer = new AnswerModel();
            if (answerId > 0)
                answer = _service.GetAnswer(answerId);
            else {
                answer.QuestionId = questionId;
            }
            return View(answer);
        }

        [Authorize(Roles = Constants.RoleAdminAppuser)]
        [ValidateAntiForgeryToken]
        public ActionResult Answers(int questionId) {
            var answers = _service.GetQuestionAnswers(questionId);
            ViewBag.QuestionId = questionId;

            var questin = _service.GetQuestion(questionId);
            ViewBag.FormId = questin.FormId;
            return View(answers);
        }

        //
        // GET: /FormBuilder/Create
        [ValidateInput(false)]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        [ValidateAntiForgeryToken]
        public ActionResult Create() {
            return View(new StudyFormModel());
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        [ValidateAntiForgeryToken]
        public ActionResult Create(StudyFormModel form) {
            try {
                // TODO: Add insert logic here
                if (ModelState.IsValid) {
                    if (string.IsNullOrWhiteSpace(form.Name) || form.Name.Length < 3) {
                        ModelState.AddModelError("Name", "Is Empty or less then 3 characters");
                        //Add other validation...
                        return View(form);
                    }
                    string name = HttpContext.User.Identity.Name;
                    form.UpdatedBy = name;
                    form.CreatedBy = name;
                    form.UpdatedOn = DateTime.UtcNow;
                    form.CreatedOn = DateTime.UtcNow;
                    if (_service != null) _service.CreateNewForm(form);
                    return RedirectToAction("Index");
                }
                return View(new StudyFormModel());
            } catch {
                return View(new StudyFormModel());
            }
        }

        //
        // GET: /FormBuilder/Details/5
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        [OutputCache(Duration = 30)]
        public ActionResult Details(int id) {
            StudyFormModel form = _service.GetForm(id, true);
            ViewBag.FormQuestions = _service.GetFormQuestions(id, true, false);
            ViewBag.LayoutType = form.LayoutType;
            return View(form);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult Edit(int id, StudyFormModel form) {
            try {
                string name = HttpContext.User.Identity.Name;
                form.UpdatedBy = name;
                form.UpdatedOn = DateTime.UtcNow;
                _service.UpdateForm(form);
                return RedirectToAction("Index");
            } catch {
                return View();
            }
        }

        //
        // GET: /FormBuilder/Edit/5
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult Edit(int id) {
            StudyFormModel form = _service.GetForm(id);
            return View(form);
        }

        //
        // GET: /FormBuilder/Delete/5
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult FormDelete(int id) {
            try {
                _service.DeleteForm(id);
                return RedirectToAction("Index");
            } catch (Exception ex) {
                ViewBag.Error = ex.InnerException.Message;
                return View();
            }
        }

        //
        // GET: /FormBuilder/
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult Index() {
            var forms = _service.GetAllForms(true);
            return View(forms);
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult QuestionDelete(int id, int fid) {
            try {
                _service.DeleteQuestion(id);
                return RedirectToAction("Questions", new { id = fid });
            } catch (Exception ex) {
                ViewBag.Error = ex.Message;
                return View();
            }
        }

        /// <summary>
        ///   Questions the edit.
        /// </summary>
        /// <param name = "question">The question.</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult QuestionEdit(QuestionModel question) {
            try {
                if (question.QuestionId == 0) {
                    question.CreatedBy = HttpContext.User.Identity.Name;
                    question.UpdatedBy = HttpContext.User.Identity.Name;
                    question.CreatedOn = DateTime.UtcNow;
                    question.UpdatedOn = DateTime.UtcNow;
                    _service.AddQuestion(question);
                } else {
                    question.UpdatedBy = HttpContext.User.Identity.Name;
                    question.UpdatedOn = DateTime.UtcNow;
                    _service.EditQuestion(question);
                }

                return RedirectToAction("Questions", new { id = question.FormId });
            } catch {
                return View(question);
            }
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult QuestionEdit(int formId, int qid) {
            var question = new QuestionModel();
            if (qid > 0)
                question = _service.GetQuestion(qid);
            else
                question.FormId = formId;

            return View(question);
        }

        /// <summary>
        ///   Manage Form Questions
        /// </summary>
        /// <param name = "id">Form ID where questions are</param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult Questions(int id) {
            ViewBag.FormName = _service.GetForm(id).Name;
            ViewBag.FormId = id;
            var questions = _service.GetFormQuestions(id);
            return View(questions);
        }
    }
}